package com.zhang.redis.util;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 *   深圳金雅福控股集团有限公司
 *  @author zhangfanjun
 * @date 2021/11/17
 * @date 2022/4/7
 */
@Component
public class RedisHelper {
    /**
     * 默认过期时间
     */
    private int defaultExpire = 30 * 24 * 60 * 60;

    /**
     * redisTemplate
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * key-value
     *
     * @author zfj
     * @date 2022/3/8
     */
    public void setValue(String key, String value) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value);
    }

    public String getStringValue(String key) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String value = valueOperations.get(key);
        return value;

    }

    /**
     * get string
     *
     * @author zfj
     * @date 2022/3/8
     */
    public Object getValue(String key) {
        Object value = redisTemplate.opsForValue().get(key);
        return value;

    }

    public <T> T getValueByType(String key, Class<T> t) {
        Object value = getValue(key);
        if (Objects.isNull(value)) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(value), t);
    }

    /**
     * key-value,seconds
     *
     * @author zfj
     * @date 2022/3/8
     */
    public void setValue(String key, Object value, long seconds) {
        if (value instanceof String) {
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key, value.toString(), seconds, TimeUnit.SECONDS);
            return;
        }
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
    }

    /**
     * 根据key删除缓存
     */
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }
}
